﻿using Microsoft.Xna.Framework;
using System;
using System.Collections.Generic;
using Terraria;
using Terraria.DataStructures;
using Terraria.Localization;
using Terraria.ModLoader;
using Terraria.ModLoader.IO;
using WorseGame.Common.Configs;

namespace WorseGame.Common.Systems
{
    public class ItemValueOverride : GlobalItem
    {
        public override bool InstancePerEntity => true;
        protected override bool CloneNewInstances => true;
        public override void SetStaticDefaults()
        {
            if (ItemConfig.Instance.DynamicPricing)
            {
                for (int i = 1; i < ItemLoader.ItemCount; i++)
                {
                    if (!DynamicPricingSystem.OriginalItemValues.ContainsKey(i))
                    {
                        Item tempItem = new();
                        tempItem.SetDefaults(i);
                        if (tempItem.value > 0)
                        {
                            DynamicPricingSystem.OriginalItemValues[i] = tempItem.value;
                        }
                    }
                }
            }
        }

        public override void UpdateInventory(Item item, Player player)
        {
            if (ItemConfig.Instance.DynamicPricing)
            {
                if (item.value > 0 && DynamicPricingSystem.ItemSalesCount.TryGetValue(item.type, out int salesCount) && DynamicPricingSystem.OriginalItemValues.TryGetValue(item.type, out int originalValue))
                {
                    float priceReduction = salesCount / 10 * 0.02f;
                    float priceMultiplier = Math.Max(1f - priceReduction, 0.5f);
                    item.value = (int)(originalValue * priceMultiplier);
                }
            }
        }

        public override void OnCreated(Item item, ItemCreationContext context)
        {
            if (ItemConfig.Instance.DynamicPricing)
            {
                if (item.value > 0 && DynamicPricingSystem.ItemSalesCount.TryGetValue(item.type, out int salesCount) && DynamicPricingSystem.OriginalItemValues.TryGetValue(item.type, out int originalValue))
                {
                    float priceReduction = salesCount / 10 * 0.02f;
                    float priceMultiplier = Math.Max(1f - priceReduction, 0.5f);
                    item.value = (int)(originalValue * priceMultiplier);
                }
            }
        }
    }
    public class DynamicPricingSystem : ModSystem
    {
        public static Dictionary<int, int> ItemSalesCount = [];
        public static Dictionary<int, int> OriginalItemValues = [];
        public override void SaveWorldData(TagCompound tag)
        {
            if (ItemConfig.Instance.DynamicPricing)
            {
                var salesData = new List<int>();
                foreach (var kvp in ItemSalesCount)
                {
                    salesData.Add(kvp.Key);
                    salesData.Add(kvp.Value);
                }
                tag["ItemSalesCount"] = salesData;
                var valueData = new List<int>();
                foreach (var kvp in OriginalItemValues)
                {
                    valueData.Add(kvp.Key);
                    valueData.Add(kvp.Value);
                }
                tag["OriginalItemValues"] = valueData;
            }
        }

        public override void LoadWorldData(TagCompound tag)
        {
            if (ItemConfig.Instance.DynamicPricing)
            {
                ItemSalesCount.Clear();
                OriginalItemValues.Clear();
                if (tag.ContainsKey("ItemSalesCount"))
                {
                    var salesData = tag.Get<List<int>>("ItemSalesCount");
                    for (int i = 0; i < salesData.Count; i += 2)
                    {
                        ItemSalesCount[salesData[i]] = salesData[i + 1];
                    }
                }
                if (tag.ContainsKey("OriginalItemValues"))
                {
                    var valueData = tag.Get<List<int>>("OriginalItemValues");
                    for (int i = 0; i < valueData.Count; i += 2)
                    {
                        OriginalItemValues[valueData[i]] = valueData[i + 1];
                    }
                }
            }
        }       
        public override void PostUpdateEverything()
        {
            if (ItemConfig.Instance.DynamicPricing)
            {
                if (Main.GameUpdateCount % 18000 == 0)
                {
                    foreach (var itemId in ItemSalesCount.Keys)
                    {
                        ItemSalesCount[itemId] = (int)(ItemSalesCount[itemId] * 0.9f);
                        if (ItemSalesCount[itemId] < 1)
                        {
                            ItemSalesCount[itemId] = 0;
                        }
                    }
                }
            }
        }
    }
    public class ShopPriceAdjuster : GlobalNPC
    {
        public override void ModifyActiveShop(NPC npc, string shopName, Item[] items)
        {
            if (ItemConfig.Instance.DynamicPricing)
            {
                foreach (Item item in items)
                {
                    if (item != null && item.value > 0 && DynamicPricingSystem.ItemSalesCount.TryGetValue(item.type, out int salesCount) && DynamicPricingSystem.OriginalItemValues.TryGetValue(item.type, out int originalValue))
                    {
                        float priceReduction = salesCount / 10 * 0.02f;
                        float priceMultiplier = Math.Max(1f - priceReduction, 0.5f);
                        item.value = (int)(originalValue * priceMultiplier);
                    }
                }
            }
        }
    }
    public class PlayerSellingHook : ModPlayer
    {
        public override void PostSellItem(NPC vendor, Item[] shopInventory, Item item)
        {
            if (ItemConfig.Instance.DynamicPricing)
            {
                if (!DynamicPricingSystem.OriginalItemValues.ContainsKey(item.type))
                {
                    Item tempItem = new();
                    tempItem.SetDefaults(item.type);
                    DynamicPricingSystem.OriginalItemValues[item.type] = tempItem.value;
                }
                if (item.value > 0)
                {
                    if (DynamicPricingSystem.ItemSalesCount.ContainsKey(item.type))
                    {
                        DynamicPricingSystem.ItemSalesCount[item.type] += item.stack;
                    }
                    else
                    {
                        DynamicPricingSystem.ItemSalesCount[item.type] = item.stack;
                    }
                    string itemName = Lang.GetItemNameValue(item.type);
                    int salesCount = DynamicPricingSystem.ItemSalesCount[item.type];
                    int priceReductionBatches = salesCount / 10;
                    float priceReduction = priceReductionBatches * 0.02f;
                    float priceReductionPercent = priceReduction * 100f;
                    if (salesCount % 10 == 0)
                    {
                        Main.NewText($"{itemName}" + Language.GetTextValue("Mods.WorseGame.NewText.Sell") + $"{priceReductionPercent:0}%", Color.Orange);
                    }
                }
            }
        }
    }
}
